package com.s1nx.back.utils;

import com.s1nx.back.exception.ServiceException;
import io.jsonwebtoken.*;

import java.util.Date;
import java.util.UUID;

public class JwtUtil {

    private static long time = 1000*6; //6 s
    private static String signature = "admin";

    public static String createToken() {
        JwtBuilder jwtBuilder = Jwts.builder();
        String jwtToken = jwtBuilder
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg","HS256")
                .claim("username","admin")
                .claim("role","admin")
                .setSubject("admin-test")
                .setExpiration(new Date(System.currentTimeMillis() + time))
                .setId(UUID.randomUUID().toString())
                .signWith(SignatureAlgorithm.HS256, signature)
                .compact();
        return jwtToken;
    }

    public static boolean checkToken(String token) {
        if (token == null) return false;
        try {
            Jwts.parser().setSigningKey(signature).parseClaimsJws(token).getBody();
        } catch (JwtException e) {
            throw new ServiceException("无效的Token");
        }
        return true;
    }

}
